package com.ayx.springcloud.controller;

import com.ayx.springcloud.entities.CommonResult;
import com.ayx.springcloud.entities.Payment;
import com.ayx.springcloud.service.PaymentService;
import com.netflix.discovery.converters.Auto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String port;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        //
        log.info("插入结果是:{}", result);
        if (result > 0) {
            return new CommonResult(200, "OK", result);
        } else {
            return new CommonResult(400, "error");
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult create(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("查询结果是:{}", payment);
        if (payment != null) {
            return new CommonResult(200, "OK" + port, payment);
        } else {
            return new CommonResult(400, "error");
        }
    }

    @GetMapping("/payment/getInfo")
    public Object getInfo() {

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("url:{}",instance.getUri());
            log.info("host:{}",instance.getHost());
            log.info("port:{}",instance.getPort());
        }
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service---------{}",service);
        }
        return this.discoveryClient;
    }
}
